<?php
use oxide\plugin\PluginAbstract;
use oxide\http\Context;
use oxide\ui\html;
use oxide\data\sql;
use module\content;
use module\user;


class ProfilePlugin extends PluginAbstract
{
   const 
      KEY_WEBSITE = 'profile_website',
      KEY_ABOUTME = 'profile_aboutme',
      KEY_FACEBOOK = 'profile_facebook',
      KEY_TWITTER = 'profile_twitter',
      KEY_GOOGLE_PLUS = 'profile_google_plus',
      KEY_COVER_IMAGE = 'profile_cover_image',
      KEY_GENDER = 'profile_gender',
      KEY_BIRTH_DAY = 'profile_birth_day',
      KEY_BIRTH_MONTH = 'profile_birth_month',
      KEY_EDU_WORK = 'profile_edu_work',
      KEY_SIGNATURE = 'profile_signature';
   

   /**
    * 
    * @param \oxide\http\Context $context
    */
   public function plug(Context $context) 
   {
      // register for notifications
      $this->register('UserDefaultUpdateForm');
      $this->register('UserDefaultUpdateDidsave');
      $this->register('UserDefaultProfileData');
      $this->register('UserDefaultProfileHeader');
      $this->register('UserDefaultProfileActivity');
   }
   
   public function onUserDefaultProfileHeader($event, $sender, $args)
   {
      $user = $args['user'];
      $cover = $user->metadata(self::KEY_COVER_IMAGE);
      if($cover) {
         echo "<img style='z-index:-1' src='{$cover}' />";
      }
   }
   
   /**
    * Show additional user activities in the user profile page
    * 
    * @param type $event
    * @param type $sender
    * @param type $args
    */
   public function onUserDefaultProfileActivity($event, $sender, $args)
   {
      $user = $args['user'];
      
      /*
       * get contents posted by the user
       */
      $query = content\model\Content::prepareSelect();
      $query->where('content.user_pk', $user->user_pk);
      $query->where('content.status', \module\content\model\Content::STATUS_ACTIVE);
      $query->order('content.modified_on', 'desc');
      $query->limit(0, 10);
      $contents = content\model\Content::select($query);

      /*
       * get tag terms by the user
       */
      $query = new sql\SelectQuery('term', oxide\data\Connection::sharedInstance());
      $query->columns(array('term', 'title'), 'term');
      $query->join('content_term', array('content_term.term_pk' => 'term.term_pk'));
      $query->join('content', array('content.content_pk' => 'content_term.content_pk'));
      $query->where('content.user_pk', $user->user_pk);
      $query->where('content.status', content\model\Content::STATUS_ACTIVE);
      $query->order('content.modified_on', 'desc');
      $query->limit(0, 20);
      $result = content\model\Tag::select($query);
      $tags = $result->fetchAll();

      /*
       * render the view script
       * and show activities in the user's profile section
       */
      $viewscript = dirname(__FILE__) . '/activities.phtml';
      $view = new oxide\application\View($viewscript);
      $view->assign('contents', $contents);
      $view->assign('tags', $tags);
      echo $view->render();
   }
   
   /**
    * Render additional profile data in the user profile's page
    * 
    * @param type $event
    * @param type $sender
    * @param type $args
    */
   public function onUserDefaultProfileData($event, $sender, $args)
   {
      $dictionary = $args['dictionary'];
      $user = $args['user'];
      
      /*
       * update user information dictionary for the profile page
       */
      $aboutme = $user->metadata(self::KEY_ABOUTME);
      $eduwork = $user->metadata(self::KEY_EDU_WORK);
      $facebook = $user->metadata(self::KEY_FACEBOOK);
      $twitter = $user->metadata(self::KEY_TWITTER);
      $website = $user->metadata(self::KEY_WEBSITE);
      


      if($aboutme) $dictionary['About me'] = $aboutme;
      if($eduwork) $dictionary['Education/Work'] = $eduwork;
      if($facebook) {
      $facebook_badge = <<< EOF
<!-- Facebook Badge START --><a href="{$facebook}" target="_TOP" style="font-family: &quot;lucida grande&quot;,tahoma,verdana,arial,sans-serif; font-size: 11px; font-variant: normal; font-style: normal; font-weight: normal; color: #3B5998; text-decoration: none;">{$facebook}</a><br/><a href="{$facebook}" target="_TOP" title=""><img src="https://badge.facebook.com/badge/100002673394200.828.1537074226.png" style="border: 0px;" /></a><br/><a href="https://www.facebook.com/badges/" target="_TOP" style="font-family: &quot;lucida grande&quot;,tahoma,verdana,arial,sans-serif; font-size: 11px; font-variant: normal; font-style: normal; font-weight: normal; color: #3B5998; text-decoration: none;" title="Make your own badge!">Create Your Badge</a><!-- Facebook Badge END -->
EOF;
         
         $dictionary['Facebook Page'] = $facebook_badge;
      }
      if($twitter) {
         $twitter_badge = <<< EOF
<a href="https://twitter.com/{$twitter}" class="twitter-follow-button" data-show-count="false" data-size="large">Follow @{$twitter}</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
EOF;
         $dictionary['Twiiter Page'] = $twitter_badge;

      }
      
      if($website) {
         $dictionary['Website'] = _html::a($website);
      }
      
   }
   
   /**
    * Add additional forms to the user update
    * 
    * @param type $event
    * @param type $sender
    * @param type $args
    */
   public function onUserDefaultUpdateForm($event, $sender, $args)
   {
      $form = $args['form'];
      $user = $args['user'];
      
      $this->addProfileInfoToUserForm($form, $user);
   }
   
   /**
    * Handle post save event of user model
    * 
    * Upload all newly registered metadata in the database
    * @param type $event
    * @param type $sender
    * @param type $args
    */
   public function onUserDefaultUpdateDidsave($event, $sender, $args)
   {
      $user = $args['user'];
      $values = $args['values'];
      $metadata = $user->metadata();
      $metadata->setData( array(
              self::KEY_ABOUTME => $values[self::KEY_ABOUTME],
              self::KEY_GENDER => $values[self::KEY_GENDER],
              self::KEY_BIRTH_DAY => $values[self::KEY_BIRTH_DAY],
              self::KEY_BIRTH_MONTH => $values[self::KEY_BIRTH_MONTH],
              self::KEY_EDU_WORK => $values[self::KEY_EDU_WORK],
              self::KEY_WEBSITE => $values[self::KEY_WEBSITE],
              self::KEY_FACEBOOK => $values[self::KEY_FACEBOOK],
              self::KEY_TWITTER => $values[self::KEY_TWITTER],
              self::KEY_GOOGLE_PLUS => $values[self::KEY_GOOGLE_PLUS],
              ));
      
      if(isset($values[self::KEY_COVER_IMAGE])) {
         $root = $_SERVER['DOCUMENT_ROOT'];
         $file = $values[self::KEY_COVER_IMAGE];

         $pos = stripos($file, $root);
         if($pos !== FALSE) {
            $len = strlen($root);
            $relative = substr($file, $len);
            $metadata->{self::KEY_COVER_IMAGE} = $relative;
         }
      }
         
      $metadata->save();
   }
   
   
   protected function addProfileInfoToUserForm(html\Form $form, module\user\model\User $user)
   {
      $pluginConfig = $this->getConfig();
      $configs = $pluginConfig->getSection($this->getPluginName());
      
      /*
       * handle user profile
       */
      // setting up the html filterer
      require_once '3rdparty/htmlpurifier/HTMLPurifier.auto.php';
      $purifierconfig = HTMLPurifier_Config::createDefault();
      $allowed_html_tags =  array('p', 'a', 'q', 'pre', 'em', 'i', 'strong', 'b', 'small', 'br');
      $allowedTagPElement = new html\Element('p', "<i>Allowed HTML tags: " . implode(', ', $allowed_html_tags));
      $purifierconfig->set('HTML.AllowedElements',$allowed_html_tags);
      $htmlTagfilterer = new oxide\validation\HtmlPurifierFilterer($purifierconfig);     
      
      // setup the input validation
      $validation = $form->getValidationProcessor();
      
      $fieldset = new html\Fieldset('info-fieldset', null, 'Additional Information');      
      $fieldset->append(new html\Element('p', 'All information is optional. Anything you add here will be publicly visible to anyone who visits your profile.  To remove information, leave fields blank.'));
      
      /*
       * adding the cover image control
       * in order for uploading to work,
       * we need to upload directory defined in the config library
       */
      $upload_dir = $this->getConfigValue('upload_dir', null);
      if(!empty($upload_dir)) {
         $upload_dir = rtrim($upload_dir, '/') . '/';
         $allowed_mimes = explode(',',$this->getConfigValue('cover_image_mimes', "image/gif, image/jpeg, image/png"));
         $allowed_mimes = array_map('trim',$allowed_mimes);
         $cover_height = $this->getConfigValue('cover_image_height', 0);
         $cover_width = $this->getConfigValue('cover_image_width', 0);
         
         // create the file control
         $coverImageControl = new html\FileControl(self::KEY_COVER_IMAGE, null, 'Cover Image');
         // add the file upload filterer
         $uploadFilterer = new \oxide\validation\file\FileUploadFilterer();
         $validation->getFiltererContainer()->addFilterer($uploadFilterer, self::KEY_COVER_IMAGE);
         // add file upload validator
         $uploadValidator = new oxide\validation\file\ImageUploadValidator($allowed_mimes);
         $uploadValidator->setMinImageSize($cover_width, $cover_height);
         $validation->getValidatorContainer()->addValidator($uploadValidator, self::KEY_COVER_IMAGE);
         // add image upload processor
         $uploadProcessor = new oxide\validation\file\ImageUploadProcessor($upload_dir, true);
         $uploadProcessor->setImageResize($cover_width, $cover_height);
         $validation->getProcessorContainer()->addProcessor($uploadProcessor, self::KEY_COVER_IMAGE);
         // add the control to the form/fieldset
         $fieldset->append($coverImageControl);
      }
      
      // about me
      $aboutControl =new html\TextareaControl(self::KEY_ABOUTME, $user->metadata(self::KEY_ABOUTME), 'About me');
      $fieldset->addControl($aboutControl);
      $fieldset->append($allowedTagPElement);
      $validation->getFilterContainer($htmlTagfilterer, self::KEY_ABOUTME); // allow some tags

      // work and eduction
      $fieldset->addControl(new html\TextareaControl(self::KEY_EDU_WORK, $user->metadata(self::KEY_EDU_WORK), 'Education and Work', null));      
      $validation->getFilterContainer($htmlTagfilterer, self::KEY_EDU_WORK); // allow some tags      
      $fieldset->append($allowedTagPElement);

      // gender
      $fieldset->addControl(new html\SelectControl(self::KEY_GENDER, $user->metadata(self::KEY_GENDER), 'Gender', null,
              array('' => '-', 'Male' => 'Male', 'Female' => 'Female')));
      // birth day + month
      $birthControl = new html\ElementControl('div', 'profile-firth-control', null, 'Birth Day & Month');
      $birthControl->append(new html\SelectControl(self::KEY_BIRTH_DAY, $user->metadata(self::KEY_BIRTH_DAY), 'Day', null,
              range(0, 31)));
      $birthControl->append(new html\SelectControl(self::KEY_BIRTH_MONTH, $user->metadata(self::KEY_BIRTH_MONTH), 'Month', null, range(0, 12)));
      $fieldset->append($birthControl);
      
      /*
       * contact info fieldset
       */
      $urlValidator = new \oxide\validation\UrlValidator();
      $validation->getValidatorContainer()->addValidator($urlValidator, [self::KEY_WEBSITE, self::KEY_FACEBOOK, self::KEY_GOOGLE_PLUS]);
      
      $fieldset->addControl(new html\InputControl('url', self::KEY_WEBSITE, $user->metadata(self::KEY_WEBSITE), 'Website link'));
      $fieldset->addControl(new html\InputControl('url', self::KEY_FACEBOOK, $user->metadata(self::KEY_FACEBOOK), 'Facebook Page link'));
      $fieldset->addControl(new html\InputControl('text', self::KEY_TWITTER, $user->metadata(self::KEY_TWITTER), 'Twitter handler'));
      $fieldset->addControl(new html\InputControl('url', self::KEY_GOOGLE_PLUS, $user->metadata(self::KEY_GOOGLE_PLUS), 'Google Plus link'));
      
      
      $form->addControl($fieldset);
   }
}
?>